# -*- coding: utf-8 -*-
from django.shortcuts import render_to_response
import urllib
import urllib2
import re
from models import Keywords,Flv,noKeywords

def reg(reg,html):
    p = re.compile(reg)
    return p.findall(html)

def main(key):
	key = urllib.quote('%s'%key.decode('utf-8').encode('GBK'))
	url = 'http://search.you.video.sina.com.cn/s?%s'
	values = {
	            'key'  : key,
	            'type' : 'video',
	            'sort' : 'click',
	        }
	data = urllib.urlencode(values)
	fullurl = url%(data.decode('utf8'))
	response = urllib2.urlopen(fullurl)
	html = response.read()
	html = html.decode('GBK')
	vid = r'vid=(\d+)'
	vidList = reg(vid,html)
	info = r'<li class="bk.*"><a href="(.*)" target="_blank"><img src="(.*)" alt=".*" title=".*" border=".*" /></a></li>'
	infolist = reg(info,html)
	downlist,downlistName = downList(vidList)
	return zip(downlist,downlistName,infolist)

def downList(vidList):
    downlist = []
    downlistName = []
    url = 'http://v.iask.com/v_play.php?vid=%s'
    for vid in vidList:
        full_url = url%vid
        response = urllib2.urlopen(full_url)
    	html = response.read()
    	html = html.decode('utf-8')
        flv = r'http.*flv'
        flvList = reg(flv,html)
        if len(flvList) == 0:
            flvList = ['']
        [downlist.append(a) for a in flvList]
        name = r'<vname><\!\[CDATA\[(.*)\]\]><\/vname>'
        nameList = reg(name,html)
        if len(nameList) == 0:
            nameList = ['视频无法观看']
        [downlistName.append(a) for a in nameList]
    return downlist,downlistName

def index(request):
    alllist = []
    isSocket = False
    key = ''
    if request.method == 'POST':
        key = request.POST['key']
        try:
            keyword = Keywords.objects.get(key = key)
        except:
            no = noKeywords()
            try:
                no.key = key
                no.save()
            except:
                pass
            if not (key == '' or key == None):
                alllist = main(key)
                isSocket = True
        else:
            alllist = Flv.objects.filter(key = keyword)
    return render_to_response('yaoflv_templates/index.html',{'all':alllist,'key':key,'isSocket':isSocket})